document.querySelector('form').addEventListener('submit', function (e) {
    e.preventDefault(); // 阻止表单的默认提交

    // 获取表单字段的值，并去除前后空格
    let username = document.getElementById('username').value.trim();
    let password = document.getElementById('password').value.trim();
    let confirmPassword = document.getElementById('confirmPassword').value.trim();
    let email = document.getElementById('email').value.trim();
    let school = document.getElementById('school').value.trim();
    let phone = document.getElementById('phone').value.trim();
    let classRoom = document.getElementById('classRoom').value.trim();

    // 校验必填字段
    if (!username || !password || !confirmPassword || !email || !school || !phone || !classRoom) {
        alert("所有字段均为必填项！");
        return;
    }

    // 校验邮箱格式
    if (!/^\S+@\S+\.\S+$/.test(email)) {
        alert("请输入有效的邮箱地址！");
        return;
    }

    // 校验手机号格式（以1开头的11位数字）
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        alert("请输入有效的手机号！");
        return;
    }

    // 校验密码一致性
    if (password !== confirmPassword) {
        alert("两次密码输入不一致！");
        return;
    }

    // 创建数据对象
    const data = { username, password, confirmPassword, email, school, phone, classRoom };

    // 发送请求到后端
    fetch("../202205070601/php/register.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/json", // 发送 JSON 数据
        },
        body: JSON.stringify(data), // 将数据转换为 JSON 字符串
    })
        .then((response) => response.json()) // 处理返回的 JSON 数据
        .then((result) => {
            if (result.success) {
                alert(result.message || "注册成功！");
                setTimeout(() => {
                    window.location.href = "../202205070601/login.html"; // 注册成功后跳转
                }, 1500);
            } else {
                alert(result.message || "注册失败，请重试！");
            }
        })
        .catch((error) => {
            console.error("请求失败:", error);
            alert("注册失败，请重试！");
        });
});
